<script>
import {addNews, delNews, editNews, getNewsByParams} from "@/apis/system/news";
import MarkdownEditor from "@/components/MarkdownEditor/index.vue";
import {baseURL} from "@/utils/request";


export default {
  name: "News",
  components: {MarkdownEditor},

  data() {
    return {
      dateRange: [],
      queryParams: {
        page: 1,
        pageSize: 5,
        newsSource: '',
        startTime: null,
        endTime: null,
        // createTime: null
      },
      total: 0,
      newsList: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      addVisible: false,
      // 图片上传的请求头
      headers: {
        token: sessionStorage.getItem("token")
      },
      action: baseURL + "/systemManager/news/upload",
      /*添加弹出层*/
      addForm: {
        imagUrl: '',
        newsTitle: '',
        newsContent: '',
        newsSource: ''
      },
      editVisible: false,
      editForm: {}
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      getNewsByParams(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        this.newsList = res.data.records
        this.total = res.data.total
      })
    },
    // 条件查询按钮
    onSubmit() {
      this.queryParams.page = 1
      this.queryParams.pageSize = 5
      if (this.queryParams.createTime != null) {
        this.queryParams.startTime = this.queryParams.createTime[0]
        this.queryParams.endTime = this.queryParams.createTime[1]
      }
      this.init()
    },
    // 重置表单
    resetForm(formName) {
      this.queryParams.page = 1
      this.queryParams.pageSize = 5
      this.queryParams.startTime = null
      this.queryParams.endTime = null
      this.queryParams.createTime = null
      this.queryParams.newsSource = ''
      this.init()
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.init()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.init()
    },
    // 头像上传成功的回调
    handleAvatarSuccess(res, file) {
      this.addForm.imagUrl = res.data;
      this.editForm.imagUrl = res.data
      this.$message({
        message: '头像成功上传！',
        type: 'success'
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 添加新闻弹出层
    addNews() {
      addNews(this.addForm).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '添加新闻成功',
            type: 'success'
          });
        }
        // 刷新表格信息
        this.init()
      })

      //  清除表单信息
      this.resetAddForm()
    },
    resetAddForm() {
      this.addForm = {
        imagUrl: '',
        newsTitle: '',
        newsContent: '',
        newsSource: ''
      }
      // 关闭弹出层
      this.addVisible = false
    },
    resetEditForm() {
      this.editForm = {}
      // 关闭弹出层
      this.editVisible = false
    },
    editClick(row) {
      this.editForm = row
      this.editVisible = true
    },
    // 确定修改
    editNews() {
      editNews(this.editForm).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '修改新闻成功',
            type: 'success'
          });
        }
        // 关闭弹窗
        this.editVisible = false
        this.init()
      })
    },
    // 删除
    delClick(row) {
      this.$confirm('此操作将永久删除该新闻, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delNews(row.newsId).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '删除成功!',
              type: 'success'
            });
          }
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    }
  }
}
</script>

<template>
  <div>
    <el-card>

      <!--查询内容-->
      <el-form ref="queryParams" :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-button type="warning" @click="addVisible=true">添加新闻</el-button>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="dateRange"
              type="dateRange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="新闻来源">
          <el-select v-model="queryParams.newsSource" placeholder="新闻来源">
            <el-option label="AAA教育" value="AAA教育"></el-option>
            <el-option label="光明日报" value="光明日报"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="resetForm('queryParams')">重置</el-button>
        </el-form-item>
      </el-form>

      <!--表格内容-->
      <el-table :data="newsList" border height="500px">
        <el-table-column prop="newsId" label="新闻ID"></el-table-column>
        <el-table-column prop="newsTitle" label="新闻标题"></el-table-column>
        <el-table-column prop="newsSource" label="新闻来源"></el-table-column>
        <el-table-column label="新闻图片">
          <template slot-scope="scope">
            <img :src="scope.row.imagUrl" style="height: 100px">
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="150">
          <template slot-scope="scope">
            <el-button @click="delClick(scope.row)" type="danger" size="small">删除</el-button>
            <el-button @click="editClick(scope.row)" type="warning" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>


      <!--分页内容-->

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[5,10,15,20]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>


    <el-dialog
        title="添加新闻"
        :visible.sync="addVisible">
      <el-form ref="form" :model="addForm" label-width="80px">
        <el-form-item label="新闻标题">
          <el-input v-model="addForm.newsTitle"></el-input>
        </el-form-item>
        <el-form-item label="新闻来源">
          <el-select v-model="addForm.newsSource" placeholder="新闻来源">
            <el-option label="AAA教育" value="AAA教育"></el-option>
            <el-option label="光明日报" value="光明日报"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="新闻内容">
          <MarkdownEditor
              ref="noticeContent"
              v-model="addForm.newsContent"
              height="300px"
              :options="{hideModeSwitch:true,previewStyle:'tab'}"
          />
        </el-form-item>
        <el-form-item label="新闻图片">
          <el-upload
              class="avatar-uploader"
              :headers="headers"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="addForm.imagUrl" :src="addForm.imagUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="resetAddForm">取 消</el-button>
    <el-button type="primary" @click="addNews">确 定</el-button>
  </span>
    </el-dialog>


    <!--  编辑新闻   -->
    <el-dialog
        title="编辑新闻"
        :visible.sync="editVisible">
      <el-form ref="form" :model="editForm" label-width="80px">
        <el-form-item label="新闻ID">
          <el-input v-model="editForm.newsId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="新闻标题">
          <el-input v-model="editForm.newsTitle"></el-input>
        </el-form-item>
        <el-form-item label="新闻来源">
          <el-select v-model="editForm.newsSource" placeholder="新闻来源">
            <el-option label="AAA教育" value="AAA教育"></el-option>
            <el-option label="光明日报" value="光明日报"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="新闻内容">
          <MarkdownEditor
              ref="noticeContent"
              v-model="editForm.newsContent"
              height="300px"
              :options="{hideModeSwitch:true,previewStyle:'tab'}"
          />
        </el-form-item>
        <el-form-item label="新闻图片">
          <el-upload
              class="avatar-uploader"
              :headers="headers"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="editForm.imagUrl" :src="editForm.imagUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="resetEditForm">取 消</el-button>
    <el-button type="primary" @click="editNews">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
